#!/bin/bash

# 仓颉仓库管理工具 (Cangjie Repo Manager) 安装脚本
# Git URL: https://gitcode.com/zichexuelan/cjdev.git

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 询问用户输入（带默认值）
ask_yes_no() {
    local prompt="$1"
    local default="${2:-n}"
    local answer
    
    if [ "$default" = "y" ]; then
        prompt="${prompt} [Y/n]: "
    else
        prompt="${prompt} [y/N]: "
    fi
    
    # 统一使用 /dev/tty 确保交互式输入正常工作（包括管道执行的情况）
    echo -n "$prompt" > /dev/tty
    read -r answer < /dev/tty
    answer="${answer:-$default}"
    
    if [[ "$answer" =~ ^[Yy]$ ]]; then
        return 0
    else
        return 1
    fi
}

# 询问用户输入文本
ask_input() {
    local prompt="$1"
    local default="$2"
    local answer
    
    if [ -n "$default" ]; then
        prompt="${prompt} [${default}]: "
    else
        prompt="${prompt}: "
    fi
    
    # 统一使用 /dev/tty 确保交互式输入正常工作（包括管道执行的情况）
    echo -n "$prompt" > /dev/tty
    read -r answer < /dev/tty
    echo "${answer:-$default}"
}

LANGUAGE_CHOICE="zh"

select_language() {
    print_info "请选择界面语言 / Choose CLI language"
    while true; do
        local selection
        selection=$(ask_input "Language (zh/en)" "$LANGUAGE_CHOICE")
        selection=$(echo "$selection" | tr 'A-Z' 'a-z')
        if [ "$selection" = "zh" ] || [ "$selection" = "en" ]; then
            LANGUAGE_CHOICE="$selection"
            break
        fi
        print_warning "无效语言，请输入 zh 或 en / Invalid language, please enter zh or en"
    done
}

save_language_config() {
    local lang="$1"
    if [ -z "$PYTHON_CMD" ]; then
        return 1
    fi
    "$PYTHON_CMD" - <<PY
import os
from pathlib import Path
import yaml

lang = "${lang}"
path = Path(os.path.expanduser("~/.cjdev.yaml"))
data = {}
if path.exists():
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f) or {}
    except Exception:
        data = {}
data["language"] = lang
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
    yaml.safe_dump(data, f, allow_unicode=True, default_flow_style=False)
PY
}

# 主安装函数
main() {
    print_info "=========================================="
    print_info "  仓颉仓库管理工具 (Cangjie Repo Manager)"
    print_info "  安装脚本"
    print_info "=========================================="
    echo ""
    
    # 检查是否在 cjdev 目录中
    if [ -f "cjdev" ] && [ -f "requirements.txt" ] && [ -d "commands" ]; then
        print_success "检测到当前目录已经是 cjdev 项目目录"
        INSTALL_DIR="$(pwd)"
    else
        # 询问是否克隆仓库
        if ask_yes_no "是否要克隆 cjdev 仓库到当前目录？" "y"; then
            INSTALL_DIR="$(pwd)/cjdev"
            
            if [ -d "cjdev" ]; then
                print_warning "目录 cjdev 已存在"
                if ask_yes_no "是否删除并重新克隆？" "n"; then
                    rm -rf cjdev
                else
                    INSTALL_DIR="$(pwd)/cjdev"
                    print_info "使用现有目录: $INSTALL_DIR"
                fi
            fi
            
            if [ ! -d "cjdev" ]; then
                print_info "正在克隆仓库..."
                if git clone https://gitcode.com/zichexuelan/cjdev.git; then
                    print_success "仓库克隆完成"
                    # 在Windows bash下，等待文件系统同步
                    sleep 1
                else
                    print_error "仓库克隆失败"
                    exit 1
                fi
            fi
        else
            print_error "请先克隆仓库或进入 cjdev 目录"
            exit 1
        fi
    fi
    
    # 确保目录存在
    if [ ! -d "$INSTALL_DIR" ]; then
        print_error "安装目录不存在: $INSTALL_DIR"
        exit 1
    fi
    
    # 切换到安装目录，如果失败则退出
    if ! cd "$INSTALL_DIR"; then
        print_error "无法切换到安装目录: $INSTALL_DIR"
        exit 1
    fi
    
    print_info "工作目录: $(pwd)"
    echo ""
    
    # 检查 Python（支持 python3 和 python）
    PYTHON_CMD=""
    if command_exists python3; then
        PYTHON_CMD="python3"
    elif command_exists python; then
        PYTHON_CMD="python"
    else
        print_error "未找到 Python，请先安装 Python 3"
        exit 1
    fi
    
    PYTHON_VERSION=$($PYTHON_CMD --version)
    print_success "找到 $PYTHON_VERSION"
    
    # 检查 pip（支持 pip3 和 pip）
    PIP_CMD=""
    if command_exists pip3; then
        PIP_CMD="pip3"
    elif command_exists pip; then
        PIP_CMD="pip"
    else
        print_error "未找到 pip，请先安装 pip"
        exit 1
    fi
    
    print_success "找到 pip"
    echo ""
    
    # 检测 macOS 并设置 pip 参数
    PIP_EXTRA_ARGS=""
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS 系统可能需要 --break-system-packages
        PIP_EXTRA_ARGS="--break-system-packages"
        print_info "检测到 macOS，将使用 --break-system-packages 参数"
    fi
    
    # 安装依赖
    print_info "正在安装 Python 依赖..."
    if $PIP_CMD install $PIP_EXTRA_ARGS -r requirements.txt; then
        print_success "依赖安装完成"
    else
        print_error "依赖安装失败"
        exit 1
    fi
    echo ""
    
    # 设置可执行权限
    print_info "设置 cjdev 可执行权限..."
    chmod +x cjdev
    chmod +x cjdev_manager.py
    print_success "可执行权限设置完成"
    echo ""
    
    # 测试 cjdev 命令
    print_info "测试 cjdev 命令..."
    if ./cjdev --version >/dev/null 2>&1; then
        print_success "cjdev 命令测试通过"
    else
        print_warning "cjdev 命令测试失败，但可能仍然可用"
    fi
    echo ""
    
    # 询问是否全局安装
    print_info "=== 全局安装选项 ==="
    if ask_yes_no "是否要将 cjdev 添加到系统 PATH（全局可用）？" "y"; then
        echo ""
        print_info "请选择安装方式："
        echo "  1) 添加到 ~/.bashrc / ~/.zshrc（推荐）"
        echo "  2) 创建软链接到 /usr/local/bin（需要 sudo）"
        echo "  3) 跳过全局安装"
        
        INSTALL_METHOD=$(ask_input "请选择 [1-3]" "1")
        
        case "$INSTALL_METHOD" in
            1)
                # 检测 shell
                SHELL_RC=""
                if [ -n "$ZSH_VERSION" ] || [ -f "$HOME/.zshrc" ]; then
                    SHELL_RC="$HOME/.zshrc"
                elif [ -n "$BASH_VERSION" ] || [ -f "$HOME/.bashrc" ]; then
                    SHELL_RC="$HOME/.bashrc"
                else
                    # 尝试检测默认 shell
                    DEFAULT_SHELL=$(basename "$SHELL")
                    if [ "$DEFAULT_SHELL" = "zsh" ]; then
                        SHELL_RC="$HOME/.zshrc"
                    else
                        SHELL_RC="$HOME/.bashrc"
                    fi
                fi
                
                if [ -z "$SHELL_RC" ] || [ ! -f "$SHELL_RC" ]; then
                    print_warning "未找到 shell 配置文件，创建 ~/.bashrc"
                    SHELL_RC="$HOME/.bashrc"
                    touch "$SHELL_RC"
                fi
                
                EXPORT_LINE="export PATH=\"$INSTALL_DIR:\$PATH\""
                
                if grep -q "$INSTALL_DIR" "$SHELL_RC" 2>/dev/null; then
                    print_warning "PATH 配置已存在于 $SHELL_RC"
                else
                    echo "" >> "$SHELL_RC"
                    echo "# cjdev - 仓颉仓库管理工具" >> "$SHELL_RC"
                    echo "$EXPORT_LINE" >> "$SHELL_RC"
                    print_success "已添加到 $SHELL_RC"
                    print_info "请运行: source $SHELL_RC 或重新打开终端"
                fi
                ;;
            2)
                if sudo ln -sf "$INSTALL_DIR/cjdev" /usr/local/bin/cjdev 2>/dev/null; then
                    print_success "软链接创建成功: /usr/local/bin/cjdev -> $INSTALL_DIR/cjdev"
                else
                    print_error "软链接创建失败（可能需要 sudo 权限）"
                fi
                ;;
            3)
                print_info "跳过全局安装"
                ;;
            *)
                print_warning "无效选择，跳过全局安装"
                ;;
        esac
    else
        print_info "跳过全局安装，你可以使用: $INSTALL_DIR/cjdev"
    fi
    echo ""
    
    # 询问是否设置 GitCode token
    print_info "=== GitCode Token 设置 ==="
    print_info "GitCode token 用于创建 Issue 和 PR（必需）"
    if ask_yes_no "是否现在设置 GitCode token？" "n"; then
        TOKEN=$(ask_input "请输入你的 GitCode token" "")
        if [ -n "$TOKEN" ]; then
            # 检测 shell 配置文件
            SHELL_RC=""
            if [ -n "$ZSH_VERSION" ] || [ -f "$HOME/.zshrc" ]; then
                SHELL_RC="$HOME/.zshrc"
            elif [ -n "$BASH_VERSION" ] || [ -f "$HOME/.bashrc" ]; then
                SHELL_RC="$HOME/.bashrc"
            else
                DEFAULT_SHELL=$(basename "$SHELL")
                if [ "$DEFAULT_SHELL" = "zsh" ]; then
                    SHELL_RC="$HOME/.zshrc"
                else
                    SHELL_RC="$HOME/.bashrc"
                fi
            fi
            
            if [ -z "$SHELL_RC" ] || [ ! -f "$SHELL_RC" ]; then
                SHELL_RC="$HOME/.bashrc"
                touch "$SHELL_RC"
            fi
            
            # 检查是否已存在
            if grep -q "gitcode_password\|gitcode_token" "$SHELL_RC" 2>/dev/null; then
                print_warning "GitCode token 配置已存在于 $SHELL_RC"
                if ask_yes_no "是否覆盖现有配置？" "n"; then
                    # 删除旧配置
                    sed -i.bak '/gitcode_password\|gitcode_token/d' "$SHELL_RC"
                else
                    print_info "保留现有配置"
                    TOKEN=""
                fi
            fi
            
            if [ -n "$TOKEN" ]; then
                echo "" >> "$SHELL_RC"
                echo "# GitCode token for cjdev" >> "$SHELL_RC"
                echo "export gitcode_token=\"$TOKEN\"" >> "$SHELL_RC"
                print_success "GitCode token 已添加到 $SHELL_RC"
                print_info "请运行: source $SHELL_RC 或重新打开终端"
            fi
        else
            print_warning "未输入 token，跳过设置"
        fi
    else
        print_info "你可以稍后手动设置:"
        print_info "  export gitcode_token=\"your_token_here\""
    fi
    echo ""

    # 语言配置
    print_info "=== 语言设置 / Language Preference ==="
    select_language
    if save_language_config "$LANGUAGE_CHOICE"; then
        if [ "$LANGUAGE_CHOICE" = "en" ]; then
            print_success "CLI language set to English (en)"
        else
            print_success "CLI 语言已设置为中文 (zh)"
        fi
    else
        print_warning "语言配置保存失败，可稍后运行 cjdev config -l <lang> 重新设置"
    fi
    echo ""
    
    # 完成提示
    print_success "=========================================="
    print_success "  安装完成！"
    print_success "=========================================="
    echo ""
    print_info "使用说明："
    echo ""
    
    if [ "$INSTALL_METHOD" = "1" ] || [ "$INSTALL_METHOD" = "2" ]; then
        print_info "  1. 如果添加了 PATH，请运行: source $SHELL_RC"
        print_info "     或重新打开终端"
        echo ""
        print_info "  2. 开始使用:"
        print_info "     cjdev init -b feature-branch -u your_username"
        print_info "     cjdev sync"
        print_info "     cjdev status"
    else
        print_info "  使用完整路径运行命令:"
        print_info "    $INSTALL_DIR/cjdev init -b feature-branch -u your_username"
        print_info "    $INSTALL_DIR/cjdev sync"
        print_info "    $INSTALL_DIR/cjdev status"
        echo ""
        print_info "  或添加临时 PATH:"
        print_info "    export PATH=\"$INSTALL_DIR:\$PATH\""
    fi
    
    echo ""
    print_info "更多信息请查看: $INSTALL_DIR/README.md"
    echo ""
}

# 运行主函数
main "$@"

